/*
 * Copyright (C) 2019 Beijing GAGO Technology Ltd.
 */

package com.logos.common.source.network.interceptor;

import com.logos.common.source.network.ExceptionHandle;
import com.logos.common.source.network.util.NetWorkUtil;
import com.logos.tool.ApplicationUtil;
import com.google.gson.JsonObject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author Young Ken
 */
public class NotNetWorkInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request.Builder builder = chain.request().newBuilder();
        Request request = builder.build();
        if (!NetWorkUtil.isNetworkAvailable(ApplicationUtil.getContext())) {
            return createNotWorkResponse(request);
        } else {
            return chain.proceed(request);
        }
    }

    public static NotNetWorkInterceptor create() {
        return new NotNetWorkInterceptor();
    }

    private Response createNotWorkResponse(Request request) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("code", ExceptionHandle.Error.NOT_NET_WORK);
        jsonObject.addProperty("data", "{}");
        ResponseBody responseBody = ResponseBody.create(mediaType, jsonObject.toString());

        return new Response.Builder()
                .request(request)
                .protocol(Protocol.HTTP_1_1)
                .code(ExceptionHandle.Error.NOT_NET_WORK)
                .message("not work")
                .body(responseBody)
                .headers(request.headers())
                .build();
    }
}
